package com.stylefeng.guns.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.common.constant.state.SpType;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.dao.PostMapper;
import com.stylefeng.guns.modular.system.model.Post;
import com.stylefeng.guns.modular.system.model.SysPrivilege;
import com.stylefeng.guns.modular.system.service.IPostService;
import com.stylefeng.guns.modular.system.service.ISysPrivilegeService;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 系统岗位表 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-09-04
 */
@Service
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {
    
    @Resource
    private PostMapper postMapper;
    
    @Resource
    private ISysPrivilegeService privilegeService;
    
    public void setAuthority(Integer postId, String ids) throws DataAccessException {
        // 删除该角色所有的权限
        Post post=this.postMapper.selectById(postId);
         if (ToolUtil.isNotEmpty(post)) {
            Wrapper<SysPrivilege> wrapper = new EntityWrapper<>();
            wrapper.eq("sp_type", SpType.POSITION.getCode());
            wrapper.eq("sp_type_id", post.getSpId());
            this.privilegeService.delete(wrapper);
        }
    
        // 添加新的权限
        for (Integer id : Convert.toIntArray(true, Convert.toStrArray(",", ids))) {
            SysPrivilege relation = new SysPrivilege();
            relation.setSpType(SpType.POSITION.getCode());//按角色划分权限
            relation.setSpFunctionId(id);
            relation.setSpTypeId(postId+"");
            relation.setSoId(post.getSoId());
            this.privilegeService.insertSysPrivilege(relation);
        }
    }
    
    public int deletePostById(Integer postId)throws DataAccessException {
        //删除角色
        this.postMapper.deleteById(postId);
        SysPrivilege relation = new SysPrivilege();
        relation.setSpType(SpType.POSITION.getCode());//按角色划分权限
        relation.setSpTypeId(postId+"");
        return this.privilegeService.deleteSysPrivilege(relation);
    }
}
